import $var from "./var.js";
import $fun from "./fun.js";
//路由
var $skip = {
	to(url, isHold = true, params = null) {
		if (params !== null) $fun.setPageParams(url, params);
		//相同地址
		let routes = getCurrentPages();
		let router = routes[routes.length - 1];
		if(router){
			router = router.route;
			if ('pages' + url == router) return false;
		}
		
		//标签带参数
		let urlParams = '';
		if(url && url[0] !== '/' && url.indexOf('?') > -1){
			let t = url.split('?');
			url = t[0];
			urlParams = '?' + t[1];
		}
		console.log(url)
		//外链
		if (url && (url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1)) {
			location.href = url;
		} else if (url == 'reload') {
			uni.startPullDownRefresh();
		} else if ($var.routes[url]) {
			if (url == 'login') { //登录时 - 清除用户缓存信息
				$fun.setCache('user_info', null)
				$fun.setCache('auth_info', null)
			}
			$skip.to($var.routes[url] + urlParams,isHold)
		}else if(url == 'goBack'){
			$skip.goBack();
		} else {
			var url = '/pages' + url;
			if (isHold === true) {
				uni.navigateTo({ //保留当前页面，跳转到应用内的某个页面
					url: url,
					fail() {
						console.log("页面保留跳转失败：" + url);
						$skip.tabar(url)
					}
				})
			} else {
				uni.redirectTo({ //关闭当前页面，跳转到应用内的某个页面
					url: url,
					fail() {
						console.log("页面清除跳转失败：" + url);
						$skip.tabar(url)
					}
				});
			}
		}
	},
	tabar(url) { //跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
		uni.switchTab({
			url: url,
			success() { return false; },
			fail() { console.log(url, '跳转到 tabBar 页面失败！...'); }
		})
	},
	goBack(level = 1) {
		// console.log(getCurrentPages().length);
		// return;
		if (getCurrentPages().length == 1) {
			$skip.to('home',false);
		} else {
			uni.navigateBack({
				delta: level
			})
		}
	},
	redirect(url) {
		uni.redirectTo({
			url: '/pages' + url
		})
	}

};

// 暴露属性和方法
export default $skip;